<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>03显示和隐藏图层</title>
  <link rel="stylesheet" href="../ol/ol.css">
  <style>
    #map {
      width: 400px;
      height: 400px;
    }
  </style>
</head>
<body>
<button onclick="toggleLayer()">显示 / 隐藏图层</button>
<div id="map"></div>

<script src="../ol/ol.js"></script>
<script>
  const map = new ol.Map({
    target: 'map',
    // 图层
    layers: [
      // 加载瓦片图
      new ol.layer.Tile({
        // 必应图源
        source: new ol.source.BingMaps({
          key: '你的Key',
          imagerySet: 'Aerial'
        })
      })
    ],
    view: new ol.View({
      center: [113.267252, 23.137949], // 设置视图中心点
      projection: 'EPSG:4326', // 配置投影坐标系
      zoom: 12, // 默认缩放级别
    })
  })

  // 显示或隐藏图层
  function toggleLayer() {
    let layers = map.getLayers() // 获取图层组
    let layer = layers.item(0) // 因为只有一个图层，所以直接 item(0) 即可拿到
    let visible = layer.getVisible() // 获取图层当前显示状态
    layer.setVisible(!visible) // 设置图层显示状态
  }
</script>
</body>
</html>